package com.exam.Controller;

//import com.baomidou.mybatisplus.core.metadata.IPage;
//import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.exam.Entity.ApiResult;
import com.exam.Entity.Score;
import com.exam.Service.ScoreService;
import com.exam.util.ApiResultHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@RestController
public class ScoreController {
    @Autowired
    private ScoreService scoreService;

    @GetMapping("/scores")
    public ApiResult findAll() {
        List<Score> res = scoreService.findAll();
        return ApiResultHandler.buildApiResult(200,"查询所有学生成绩",res);
    }
//    分页
    @GetMapping("/score/{page}/{size}/{studentId}")
    public ApiResult findByIdPage(@PathVariable("page") Integer page, @PathVariable("size") Integer size, @PathVariable("studentId") Integer studentId) {
//        Page<Score> scorePage = new Page<>(page, size);
//        IPage<Score> res = scoreService.findById(scorePage, studentId);
//        return ApiResultHandler.buildApiResult(200, "根据ID查询成绩", res);
        ApiResult apiResult;
        List<Score> res = scoreService.findByIdPage(studentId,page,size);
        List<Score> t= scoreService.findTotal(studentId,page,size);
        System.out.println("score表分页查询到了");
        // 构造返回数据
        Map<String, Object> data = new java.util.HashMap<>();
        data.put("records", res);               // 返回的试卷列表
        data.put("current", page);              // 当前页码
        data.put("size", size);                 // 每页大小
        data.put("total", t.size());          // 总记录数（列表长度）

        // 构建 ApiResult
        apiResult = ApiResultHandler.buildApiResult(200, "请求成功！", data);

        return apiResult;
    }
//    不分页
    @GetMapping("/score/{studentId}")
        public ApiResult findById(@PathVariable("studentId") Integer studentId) {
        List<Score> res = scoreService.findById(studentId);
        if (!res.isEmpty()) {
            return ApiResultHandler.buildApiResult(200, "根据ID查询成绩", res);
        } else {
            return ApiResultHandler.buildApiResult(400, "ID不存在", res);
        }
    }

    @PostMapping("/score")
    public ApiResult add(@RequestBody Score score) {
        int res = scoreService.add(score);
        if (res == 0) {
            return ApiResultHandler.buildApiResult(400,"成绩添加失败",null);
        }else {
            return ApiResultHandler.buildApiResult(200,"成绩添加成功",Collections.singletonMap("scoreID", score.getScoreId()));
        }
    }

    @GetMapping("/scores/{examCode}")
    public ApiResult findByExamCode(@PathVariable("examCode") Integer examCode) {
        List<Score> scores = scoreService.findByExamCode(examCode);
        return ApiResultHandler.buildApiResult(200,"查询成功",scores);
    }
}
